<!--
  * 登录
  *
  * @Author:    
  * @Date:  
  * @Email:     
  * @Copyright  
  *
-->
<template>
  <div class="login-container">
    <div class="box-item login">
      <div class="welcome">
        <p>欢迎登录后台管理系统</p>
      </div>
      <div class="login-title">账号登录</div>
      <a-form ref="formRef" class="login-form" :model="loginForm" :rules="rules">
        <a-form-item name="loginName">
          <a-input v-model:value.trim="loginForm.loginName" placeholder="请输入用户名" />
        </a-form-item>
        <a-form-item name="emailCode" v-if="emailCodeShowFlag">
          <a-input-group compact>
            <a-input
              style="width: calc(100% - 110px)"
              v-model:value="loginForm.emailCode"
              autocomplete="on"
              placeholder="请输入邮箱验证码"
            />
            <a-button
              @click="sendSmsCode"
              class="code-btn"
              type="primary"
              :disabled="emailCodeButtonDisabled"
            >
              {{ emailCodeTips }}
            </a-button>
          </a-input-group>
        </a-form-item>
        <a-form-item name="password">
          <a-input-password
            v-model:value="loginForm.password"
            autocomplete="on"
            :type="showPassword ? 'text' : 'password'"
            placeholder="请输入密码：至少三种字符，最小 8 位"
          />
        </a-form-item>
        <!-- <a-form-item name="captchaCode">
          <a-input
            class="captcha-input"
            v-model:value.trim="loginForm.captchaCode"
            placeholder="请输入验证码"
          />
          <img class="captcha-img" :src="captchaBase64Image" @click="getCaptcha" />
        </a-form-item> -->
        <a-form-item>
          <a-checkbox v-model:checked="rememberPwd">记住密码</a-checkbox>
        </a-form-item>
        <a-form-item>
          <div class="btn" @click="onLogin">登录</div>
        </a-form-item>
      </a-form>
    </div>
  </div>
</template>
<script setup>
import { message } from "ant-design-vue";
import { onMounted, onUnmounted, reactive, ref } from "vue";
import { useRouter } from "vue-router";
import { UserAPI } from "/@/api/xstage/user.js";
import { LxLoading } from "/@/components/framework/lx-loading";
import { LOGIN_DEVICE_ENUM } from "../../../constants/login-device-const.js";
import { useUserStore } from "/@/store/modules/system/user";

import { buildRoutes } from "/@/router/index";
import { lxSentry } from "/@/lib/lx-sentry";
import { encryptData } from "/@/lib/encrypt";
import { useDictStore } from "/@/store/modules/system/dict.js";
import { DictAPI } from "/@/api/xstage/dict.js";
import { ApiUtil } from "/@/utils/api";

//--------------------- 登录表单 ---------------------------------

const loginForm = reactive({
  loginName: "admin",
  password: "",
  captchaCode: "",
  captchaUuid: "",
  loginDevice: LOGIN_DEVICE_ENUM.PC.value,
});
const rules = {
  loginName: [{ required: true, message: "用户名不能为空" }],
  password: [{ required: true, message: "密码不能为空" }],
  captchaCode: [{ required: true, message: "验证码不能为空" }],
};

const showPassword = ref(false);
const router = useRouter();
const formRef = ref();
const rememberPwd = ref(false);

onMounted(() => {
  document.onkeyup = (e) => {
    if (e.keyCode === 13) {
      onLogin();
    }
  };
});

onUnmounted(() => {
  document.onkeyup = null;
});

//登录
async function onLogin() {
  formRef.value.validate().then(async () => {
    try {
      LxLoading.show();
      // 密码加密
      let encryptPasswordForm = Object.assign(
        {},
        {
          account: loginForm.loginName,
          password: loginForm.password,
        },
        {
          // password: encryptData(loginForm.password),
        }
      );
      const res = await UserAPI.loginUser(encryptPasswordForm);
      console.log(res);
      stopRefreshCaptchaInterval();
      // 设置token
      useUserStore().setToken(res.data.data.token || "");
      message.success("登录成功");
      //更新用户信息到pinia
      await useUserStore().setUserLoginInfo(res.data.data);

      // 初始化数据字典
      const dictRes = await DictAPI.listDict({ ...ApiUtil.getTotalDataParams() });
      useDictStore().initData(dictRes.list);

      //构建系统的路由
      buildRoutes();
      router.push("/home");
    } catch (e) {
      if (e.data && e.data.code !== 0) {
        loginForm.captchaCode = "";
        // getCaptcha();
      }
      lxSentry.captureError(e);
    } finally {
      LxLoading.hide();
    }
  });
}

//--------------------- 验证码 ---------------------------------

const captchaBase64Image = ref("");
async function getCaptcha() {
  try {
    let captchaResult = await UserAPI.getCaptcha();
    captchaBase64Image.value = captchaResult.data.captchaBase64Image;
    loginForm.captchaUuid = captchaResult.data.captchaUuid;
    beginRefreshCaptchaInterval(captchaResult.data.expireSeconds);
  } catch (e) {
    console.log(e);
  }
}

let refreshCaptchaInterval = null;
function beginRefreshCaptchaInterval(expireSeconds) {
  if (refreshCaptchaInterval === null) {
    refreshCaptchaInterval = setInterval(getCaptcha, (expireSeconds - 5) * 1000);
  }
}

function stopRefreshCaptchaInterval() {
  if (refreshCaptchaInterval != null) {
    clearInterval(refreshCaptchaInterval);
    refreshCaptchaInterval = null;
  }
}

onMounted(() => {
  // getCaptcha();
  // getTwoFactorLoginFlag();
});

//--------------------- 邮箱验证码 ---------------------------------

const emailCodeShowFlag = ref(false);
let emailCodeTips = ref("获取邮箱验证码");
let emailCodeButtonDisabled = ref(false);
// 定时器
let countDownTimer = null;
// 开始倒计时
function runCountDown() {
  emailCodeButtonDisabled.value = true;
  let countDown = 60;
  emailCodeTips.value = `${countDown}秒后重新获取`;
  countDownTimer = setInterval(() => {
    if (countDown > 1) {
      countDown--;
      emailCodeTips.value = `${countDown}秒后重新获取`;
    } else {
      clearInterval(countDownTimer);
      emailCodeButtonDisabled.value = false;
      emailCodeTips.value = "获取验证码";
    }
  }, 1000);
}

// 获取双因子登录标识
async function getTwoFactorLoginFlag() {
  try {
    let result = await UserAPI.getTwoFactorLoginFlag();
    emailCodeShowFlag.value = result.data;
  } catch (e) {
    lxSentry.captureError(e);
  }
}

// 发送邮箱验证码
async function sendSmsCode() {
  try {
    LxLoading.show();
    let result = await UserAPI.sendLoginEmailCode(loginForm.loginName);
    message.success("验证码发送成功!请登录邮箱查看验证码~");
    runCountDown();
  } catch (e) {
    lxSentry.captureError(e);
  } finally {
    LxLoading.hide();
  }
}
</script>
<style lang="less" scoped>
@import "./login.less";
</style>
